import { addHistoryApi, addFavoriteApi, delFavoriteApi, addLtvApi } from "../../api/user";
import { aboutUser } from "../../store";

const { getPlayletManager } = tt;

Component({
  pm: undefined,

  data: { userInfo: {}, playerShow: false, emitTimesPlayer: 0, currentTime: 0, nowVideoNum: 0 },

  inject: ["playerTap"],

  observers: {
    // 点击组件 A 的 button 后，触发该监听器的执行
    playerTap(val) {
      this.setData({ emitTimesPlayer: val });
    },
  },

  ready() {
    const userInfo = aboutUser.getUserInfo();
    this.setData({ userInfo });

    const pm = getPlayletManager();
    this.pm = pm;

    const pages = getCurrentPages();
    const options = pages[pages.length - 1].options; // 获取当前页面

    pm.onPlay((e) => {
      console.log("触发开始播放onPlay回调，时间是:", new Date());

      this.setData({ nowVideoNum: e.seq });

      pm.getPlayletInfo().then((res) => {
        aboutUser.saveUserData({ historyData: { vid: options.vid, episodeId: res.episodeId } });
        addHistoryApi({ userId: userInfo.userId, videoId: options.vid, num: res.seq });
      });
    });

    pm.onPause((e) => {
      this.printLog("触发暂停播放onPause回调:", JSON.stringify(e, null, 2));
    });

    pm.onEnded((e) => {
      this.printLog("触发播放到末尾onEnded回调:", JSON.stringify(e, null, 2));
      aboutUser.addPointFun("watchNum");
    });

    pm.onError((e) => {
      console.error("触发onError回调,请确认2", e);
      // tt.showModal({ title: "触发onError回调,请确认", content: JSON.stringify(e), showCancel: false });
      this.printLog("触发onError回调:", JSON.stringify(e, null, 2));
    });

    pm.onTimeUpdate((e) => {
      // 播放进度变化时触发，返回当前播放时间点及视频总时长，单位：秒(s)。event.detail = { currentTime, duration }。
      this.setData({ currentTime: e.currentTime.toFixed(0) });

      this.printLog("触发播放进度变化onTimeUpdate回调:", JSON.stringify(e, null, 2));
    });

    pm.onWaiting((e) => {
      this.printLog("触发视频出现缓冲onWaiting回调:", JSON.stringify(e, null, 2));
    });

    pm.onPlayBackRateChange((e) => {
      this.printLog("触发视频倍速改变onPlayBackRateChange回调:", JSON.stringify(e, null, 2));
    });

    pm.onLoadedMetaData((e) => {
      this.printLog("触发视频元数据加载完成onLoadedMetaData回调:", JSON.stringify(e, null, 2));
    });

    pm.onSeekComplete((e) => {
      this.printLog("触发seek完成onSeekComplete回调:", JSON.stringify(e, null, 2));
    });

    pm.onMuteChange((e) => {
      this.printLog("触发静音状态改变onMuteChange回调:", JSON.stringify(e, null, 2));
    });

    pm.onControlTap((e) => {
      console.log("触发点击控件onControlTap回调", e);
      let params = { userId: userInfo.userId, videoId: options.vid };

      e.controlType == "subscribe" && addFavoriteApi(params);
      e.controlType == "unsubscribe" && delFavoriteApi(params);
    });

    pm.onOpenCatalog((e) => {
      this.printLog("触发点击选集onOpenCatalog回调:", JSON.stringify(e, null, 2));
    });

    pm.onChangeEpisode((e) => {
      this.setData({ seq: e.seq });

      pm.getPlayletInfo().then((res) => {
        this.setData({ tt_album_id: res.albumId, tt_episode_id: res.episodeId, seq: res.seq });
      });

      e.status == "lock" && this.pm.toggleCustomDialog();

      try {
        addLtvApi({ upNum: this.data.nowVideoNum, videoId: options.vid, time: this.data.currentTime });
        this.setData({ currentTime: 0 });
      } catch {}

      console.log("触发选集切换onChangeEpisode回调:", e);
    });

    pm.onClickUnlock((e) => {
      this.printLog("触发点击解锁按钮onClickUnlock回调:", JSON.stringify(e, null, 2));
      this.pm.toggleCustomDialog();
    });

    pm.onTapCustomIcon((e) => {
      console.log("触发点击自定义组件onTapCustomIcon回调");
      this.printLog("触发点击自定义组件onTapCustomIcon回调:", JSON.stringify(e, null, 2));
      pm.setConfig({
        activityInfo: [
          {
            icon: this.data.playerShow
              ? "https://img95.699pic.com/xsj/0c/1m/7e.jpg%21/fw/700/watermark/url/L3hzai93YXRlcl9kZXRhaWwyLnBuZw/align/southeast"
              : "https://img1.baidu.com/it/u=4277336598,3522277563&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800",
            title: this.data.playerShow ? "开辅助" : "关辅助",
          },
        ],
      });
      this.setData({
        playerShow: !this.data.playerShow,
      });
    });

    pm.onTapShare((e) => {
      console.log(`tt_album_id=${this.data.albumId}&tt_episode_id=${this.data.episodeId}`);
      return {
        // 分享数据
        title: "觅得剧场", // 这是要转发的小程序标题
        desc: `这是默认的转发文案，用户可以直接发送，也可以在发布器内修改,分享的episodeId是 ${this.data.tt_episode_id}`,
        path: `/page/playlet-extension/index?tt_album_id=${this.data.tt_album_id}&tt_episode_id=${this.data.tt_episode_id}`, // ?后面的参数会在转发页面打开时传入onLoad方法
        imageUrl: "https://n.sinaimg.cn/sinakd20220105s/289/w945h944/20220105/d698-6b9d8808d51527dc9656b35e12b486ae.jpg", // 支持本地或远程图片，默认是小程序 icon
        templateId: "这是开发者后台设置的分享素材模板id",
      };
    });

    pm.onShareSuccess((res) => {
      console.log("shareSuccess-uuuu", res);
      this.printLog("分享成功onShareSuccess回调:", JSON.stringify(res, null, 2));
    });

    pm.onShareFail((res) => {
      console.log("shareFail-uuuu", err);
      this.printLog("分享失败onShareSuccess回调:", JSON.stringify(res, null, 2));
    });
  },
  methods: {
    emitInfoToParent() {
      const instance = this.selectOwnerComponent();
      instance.showOnTimeUpdateChange("player");
    },

    // 是否显示OnTimeUpdata日志
    showOnTimeUpdateChange() {
      this.setData({
        showOnTimeUpdate: !this.data.showOnTimeUpdate,
      });
    },

    // 是都显示简易日志
    showDetailChange() {
      this.setData({
        showDetail: !this.data.showDetail,
      });
    },

    // 获取当前剧目信息
    getPlayletInfo() {
      this.pm.getPlayletInfo().then((res) => {
        this.printLog("调用获取当前剧目信息getPlayletInfo:", JSON.stringify(res, null, 2));
      });
    },

    //调用播放
    setPlayStatusPlay(e) {
      console.log("调用播放方法", e);
      this.pm.setPlayStatus("play");
    },

    //调用暂停
    setPlayStatusPause(e) {
      console.log("调用暂停方法", e);
      this.pm.setPlayStatus("pause");
    },

    // 清除日志
    clearLog() {
      this.setData({
        log: "", // 日志
        logDetail: "", //详细日志
        logWithoutOnTimeUpdate: "", // 日志去除OnTimeUpdate
        logDetailWithoutOnTimeUpdate: "", //详细日志去除OnTimeUpdate
      });
    },

    // log输出
    printLog(mes, callbackData) {
      var date = new Date();
      let time = "【" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds() + ":" + date.getMilliseconds() + "】";

      if (mes.includes("onTimeUpdate")) {
        this.setData({
          log: (time + mes + "\n" + this.data.log).substr(0, 10000),
          logDetail: (time + mes + "\n" + callbackData + "\n" + this.data.logDetail).substr(0, 10000),
        });
      } else {
        this.setData({
          log: (time + mes + "\n" + this.data.log).substr(0, 10000),
          logDetail: (time + mes + "\n" + callbackData + "\n" + this.data.logDetail).substr(0, 10000),
          logWithoutOnTimeUpdate: (time + mes + "\n" + this.data.logWithoutOnTimeUpdate).substr(0, 10000),
          logDetailWithoutOnTimeUpdate: (time + mes + "\n" + callbackData + "\n" + this.data.logDetailWithoutOnTimeUpdate).substr(0, 10000),
        });

        // console.log(mes + callbackData);
      }
    },
  },
});
